package com.weimei.conversionTreasure.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;

import com.csyuejia.paylib.PayUtils;
import com.csyuejia.paylib.alipay.Alipay;
import com.csyuejia.paylib.wxpay.WXPay;
import com.gtdev5.geetolsdk.mylibrary.beans.Gds;
import com.gtdev5.geetolsdk.mylibrary.beans.UpdateBean;
import com.gtdev5.geetolsdk.mylibrary.callback.BaseCallback;
import com.gtdev5.geetolsdk.mylibrary.http.HttpUtils;
import com.gtdev5.geetolsdk.mylibrary.util.DataSaveUtils;
import com.weimei.conversionTreasure.R;
import com.weimei.conversionTreasure.adapter.VipAdapter;
import com.weimei.conversionTreasure.databinding.ActivityVipBinding;
import com.weimei.conversionTreasure.http.entity.OdBean;
import com.weimei.conversionTreasure.utils.GlideHandler;
import com.weimei.conversionTreasure.utils.UserUtils;
import com.weimei.conversionTreasure.viewModel.VipVM;

import java.util.List;

import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.tatarka.bindingcollectionadapter2.BR;
import okhttp3.Request;
import okhttp3.Response;

public class VipActivity extends BaseActivity<ActivityVipBinding, VipVM> {

    VipAdapter vipAdapter;
    List<Gds> list;
    int payWay = 2;
    int gId;


    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_vip;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    protected void onResume() {
        super.onResume();
        GlideHandler.loadUserHead(this, UserUtils.getUserImg(),10,binding.head);
        binding.name.setText(UserUtils.getUserName());
        binding.vipTime.setText(UserUtils.getVipEndTime());
    }

    @Override
    public void initData() {
        super.initData();
        vipAdapter = new VipAdapter();
        binding.vipRecy.setAdapter(vipAdapter);

//        if (DataSaveUtils.getInstance().isVip()){
//            viewModel.vipTime.set("会员到期时间："+DataSaveUtils.getInstance().getVip().getTime());
//        }


        list = DataSaveUtils.getInstance().getAllGds();
        if (list.size()> 0){
            viewModel.price.set(list.get(0).getPrice());
            gId = list.get(0).getGid();
            vipAdapter.setList(list);
        }

        vipAdapter.addChildClickViewIds(R.id.item);
        vipAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            vipAdapter.setSel(position);
            viewModel.price.set(list.get(position).getPrice());
            gId = list.get(position).getGid();
        });

        binding.cbWx.setOnClickListener(view -> {
            if (binding.cbWx.isChecked()) {
                payWay = 1;
                binding.cbZfb.setChecked(false);
            } else {
                binding.cbWx.setChecked(true);
            }
        });

        binding.cbZfb.setOnClickListener(view -> {
            if (binding.cbZfb.isChecked()) {
                payWay = 2;
                binding.cbWx.setChecked(false);
            } else {
                binding.cbZfb.setChecked(true);
            }
        });

        binding.pay.setOnClickListener(view -> {
            if (binding.box.isChecked()){
                pay();
            }else {
                ToastUtils.showShort("请先阅读并同意会员用户协议");
            }
        });

        binding.tvUser.setOnClickListener(view -> {
            Intent bundle = new Intent(this,WebActivity.class);
            bundle.putExtra("flag", "VIP");
            startActivity(bundle);
        });
    }

    private void pay() {
        HttpUtils.getInstance().PostOdOrder(1, gId, 0, payWay, new BaseCallback<OdBean>() {
            @Override
            public void onRequestBefore() {

            }

            @Override
            public void onFailure(Request request, Exception e) {

            }

            @Override
            public void onSuccess(Response response, OdBean odResultBean) {
                if (odResultBean.isIssucc()){
                    ToastUtils.showShort("支付中");
                    if (payWay == 1) {
                        payWx(odResultBean);
                    }else if (payWay == 2) {
                        payAli(odResultBean);
                    }
                }else {
                    ToastUtils.showShort(odResultBean.getMsg());
                }

            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {

            }
        });
    }

    private void payAli(OdBean o) {
        new Alipay(this, o.getPackageStr(), new Alipay.AlipayResultCallBack() {
            @Override
            public void onSuccess() {
                GTUpdate();
            }

            @Override
            public void onDealing() {
                ToastUtils.showShort("支付处理中...");

            }

            @Override
            public void onError(int error_code) {
                switch (error_code) {
                    case Alipay.ERROR_RESULT:
                        ToastUtils.showShort("支付失败:支付结果解析错误");
                        break;
                    case Alipay.ERROR_NETWORK:
                        ToastUtils.showShort("支付失败:网络连接错误");
                        break;
                    case Alipay.ERROR_PAY:
                        ToastUtils.showShort("支付错误:支付宝支付失败");
                        break;
                    default:
                        ToastUtils.showShort("支付错误");
                        break;
                }

            }

            @Override
            public void onCancel() {
                ToastUtils.showShort("支付取消");

            }
        }).doPay();
    }

    private void payWx(OdBean o) {
        String payParam = PayUtils.getJson(
                new String[]{"appid", "partnerid", "prepayid", "package", "noncestr", "timestamp", "sign"},
                new String[]{
                        o.getAppid(),
                        o.getPartnerId(),
                        o.getPrepayid(),
                        o.getPackageStr(),
                        o.getNonceStr(),
                        o.getTimestramp(),
                        o.getSign()});
        WXPay.init(this, o.getAppid());      // 要在支付前调用

        WXPay.getInstance().doPay(payParam, new WXPay.WXPayResultCallBack() {
            @Override
            public void onSuccess() {
                ToastUtils.showShort("支付成功");
                GTUpdate();
            }

            @Override
            public void onError(int error_code) {
                switch (error_code) {
                    case WXPay.NO_OR_LOW_WX:
                        break;
                    case WXPay.ERROR_PAY_PARAM:
                        break;
                    case WXPay.ERROR_PAY:
                        break;
                }
            }

            @Override
            public void onCancel() {
                ToastUtils.showShort("支付取消");
            }
        });
    }

    private void GTUpdate() {
        HttpUtils.getInstance().postUpdate(new BaseCallback<UpdateBean>() {
            @Override
            public void onRequestBefore() {

            }

            @Override
            public void onFailure(Request request, Exception e) {
            }

            @Override
            public void onSuccess(Response response, UpdateBean updateBean) {
                if (updateBean.getIssucc()) {
                    if (updateBean != null) {
                        DataSaveUtils.getInstance().saveAppData(updateBean);
                        UserUtils.setVip(updateBean.getVip());
                        if (DataSaveUtils.getInstance().isVip()){
                            viewModel.vipTime.set("会员到期时间："+DataSaveUtils.getInstance().getVip().getTime());
                        }
                    }
                }
            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {

            }
        });
    }

}

